const list = document.querySelector(".list");
const _modal = document.getElementById("modal");
const modal = new bootstrap.Modal(_modal);
const province = document.querySelector('[name="province"]');
const city = document.querySelector('[name="city"]');
const area = document.querySelector('[name="area"]');
const form = document.querySelector("#form");
const modaltitle = document.querySelector(".modal-title");
// 初始化
function init() {
  getList();
  getProvince();
  province.addEventListener("change", async function (e) {
    getCity(province.value);
  });
  city.addEventListener("change", async function (e) {
    getArea(province.value, city.value);
  });
}
init();
//学生列表渲染
async function getList() {
  const res = await axios({
    url: "/students",
  });
  // console.log(res);
  // if (res.status == 200) {
  //   myToast.show();
  //   toast.innerHTML = res.data.message;
  // }
  const data = res.data.data;
  const newData = data.map(
    (item) => `
  <tr>
                <td>${item.name}</td>
                <td>${item.age}</td>
                <td>${item.gender === 0 ? "男" : "女"}</td>
                <td>第${item.group}组</td>
                <td>${item.hope_salary}</td>
                <td>${item.salary}</td>
                <td>${item.province + item.city + item.area}</td>
                <td>
                  <a href="javascript:;" class="text-success mr-3"><i data-id="${
                    item.id
                  }" class="bi bi-pen"></i></a>
                  <a  href="javascript:;" class="text-danger"><i data-id="${
                    item.id
                  }" class="bi bi-trash"></i></a>
                </td>
              </tr>
  `
  );
  list.innerHTML = newData.join("");
  document.querySelector(".total").innerHTML = data.length;
}
//获取省份
async function getProvince() {
  const res = await axios({
    url: "/api/province",
  });
  data = res.data.data;
  const arr = data.map(
    (item) => `
  <option value="${item}">${item}</option>
  `
  );
  province.innerHTML =
    `<option value="">--省份--</option>` + arr.join("");
}
//获取城市
async function getCity(pname) {
  const res = await axios({
    url: "/api/city",
    params: { pname },
  });
  data = res.data.data;
  const arr = data.map(
    (item) => `
  <option value="${item}">${item}</option>
  `
  );
  city.innerHTML = `<option value="">--城市--</option>` + arr.join("");
  area.innerHTML = `<option value="">--地区--</option>`;
}
//获取地区
async function getArea(pname, cname) {
  const res = await axios({
    url: "/api/area",
    params: { pname, cname },
  });
  // console.log(res.data.data);
  data = res.data.data;
  const arr = data.map(
    (item) => `
  <option value="${item}">${item}</option>
  `
  );
  area.innerHTML = `<option value="">--地区--</option>` + arr.join("");
}
//打开模态框
document.querySelector("#openModal").addEventListener("click", () => {
  modal.show();
  modaltitle.innerText = "添加学员"
});
//模态框提交
form.addEventListener("submit", async function (e) {
  e.preventDefault()
  const data = serialize(form, { hash: true, empty: true });
  for (const key in data) {
      if (isNaN(data[key])==false) {
        // console.log(data[key]);
        data[key] = +data[key];
      }
    }
  console.log(data);
  let res
  if (modaltitle.innerText === "添加学员") {
    // delete data.id
    res = await axios({
      url: "/students",
      method: "post",
      data,
    })
  }else{
    // delete data.id
    res=await axios({
      url:`/students/${data.id}`,
      method:'PUT',
      data
    })
    console.log(res);
  }
    if (res.status==201||res.status==200) {
      myToast.show();
      toast.innerHTML = res.data.message
      modal.hide();
      form.reset()
      getList()
    }
  
});
//点击编辑和修改
list.addEventListener('click',async function(e){
  const id=e.target.dataset.id
  if (e.target.classList.contains('bi-pen')) {
    modal.show();
    modaltitle.innerText = "修改学员"
    const res=await axios({
      url:`/students/${id}`,
    })
    // console.log(res);
    if (res.status==200) {
      myToast.show();
      toast.innerHTML = res.data.message
    }
    // const data = serialize(form, { hash: true, empty: true });
    // console.log(res);
    const data=res.data.data
    const nameList=form.querySelectorAll('[name]')
    await getCity(data.province)
    await getArea(data.province, data.city);
    nameList.forEach(ele => {
      if (ele.name!=='gender') {
        form.querySelector(`[name=${ele.name}]`).value=data[ele.name]
      }
    });
    form.querySelector(`[name="gender"][value='${data.gender}']`).checked=true
  }else if (e.target.classList.contains('bi-trash')) {
    const res=await axios({
      url:`/students/${id}`,
      method:'DELETE',
      params:{id}
    })
    console.log(res);
    if (res.status==204) {
      myToast.show();
      toast.innerHTML = '删除学员成功'
      getList()
    }
  }
})
